package com.szq.netty.redis;

import com.alibaba.fastjson.JSON;
import com.szq.netty.domain.UserChannelInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: RedisUtil
 * @Description:
 * @Author: szq
 * @Date: 2021-11-18 15:45:01
 */
@Service("redisUtil")
public class RedisUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final static String redisKey = "netty-demo-209-user";

    public void pushObj(UserChannelInfo userChannelInfo){
        redisTemplate.opsForHash().put(redisKey, userChannelInfo.getChannelId(), JSON.toJSONString(userChannelInfo));
    }

    public List<UserChannelInfo> popList(){
        List<UserChannelInfo> userChannelInfoList = new ArrayList<>();
        List<Object> values = redisTemplate.opsForHash().values(redisKey);
        values.stream().forEach(t->{
            userChannelInfoList.add(JSON.parseObject(t.toString(), UserChannelInfo.class));
        });
        return userChannelInfoList;
    }

    public void remove(String channelId){
        redisTemplate.opsForHash().delete(redisKey, channelId);
    }

    public void clear(){
        redisTemplate.delete(redisKey);
    }
}
